#include "logui.h"
#include "ui_logui.h"

logUI::logUI(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::logUI)
{
    ui->setupUi(this);

    this->setFixedSize(this->size());

    if(init() == false){//如果数据库打开失败
        QMessageBox::warning(0,"警告","数据库打开失败!请检查数据库设置.");
        ui->btnLog->setEnabled(false);
        ui->btnRegister->setEnabled(false);
    }



}

logUI::~logUI()
{
    delete ui;
}

bool logUI::init()
{
    m_db = QSqlDatabase::addDatabase("QMYSQL");
    m_db.setDatabaseName("db_bookSys");
    m_db.setHostName("localhost");
    m_db.setUserName("root");
    m_db.setPassword("KWP-ffmxyr0");
    if(m_db.open() == true){
        return true;//打开数据库成功返回true
    }
    else{
        return false;
    }
}

void logUI::on_btnLog_clicked()
{
    m_role = 0;//默认登陆为管理员账号

    QString account = ui->editAccount->text();
    QString pswd = ui->editPswd->text();
    if(account.simplified().isEmpty()){//如果账号为空
        QMessageBox::information(0,"提示","账号不能为空.");
        return;
    }
    if(pswd.simplified().isEmpty()){//如果密码为空
        QMessageBox::information(0,"提示","密码不能为空.");
        return;
    }

    QSqlQuery query;
    query.exec("select pswd from tb_admin where account='"+account+"';");
    if(query.size() == 0){//如果在管理员表中没有找到该账号则在用户表中查找
        m_role = 1;
        query.exec("select pswd from tb_user where account='"+account+"';");
        if(query.size() == 0){//如果在用户表中也没有找到该账号,则账号输入错误
            QMessageBox::warning(0,"警告","账号输入错误.");
            return;
        }
    }

    //如果查询到该账号的密码
    query.first();

    if(query.isValid() && pswd != query.value("pswd").toString()){
        QMessageBox::warning(0,"警告","密码输入错误!");
        return;
    }



    this->close();
    MainWindow* m = new MainWindow(account,m_role,&m_db);
    m->show();

}


void logUI::on_btnRegister_clicked()
{
    myregister m;
    m.exec();
}

